import { Alert, Badge, Card, Flex, Spin } from 'antd'
import { useEffect, useState } from 'react'

/**
 * @abstract 编程环境卡片
 */
export default function EnvPanel() {
  const [error, setError] = useState<Error | null>(null)
  const [envInfoData, setEnvInfoData] = useState<Record<string, any> | undefined>(undefined)
  const [loading, setLoading] = useState<boolean>(true) // 引入加载状态
  const fetchEnvData = async () => {
    try {
      setLoading(true) // 开始加载时设置 loading 为 true
      const envInfo = await window.api.envInfo()
      setEnvInfoData(envInfo)
    } catch (err) {
      if (err instanceof Error) {
        // 确保 err 是 Error 类型
        setError(err)
      } else {
        // 将非 Error 类型的错误转换为 Error 对象
        setError(new Error(String(err)))
      }
    } finally {
      setLoading(false) // 加载完成后设置 loading 为 false
    }
  }
  useEffect(() => {
    fetchEnvData()
  }, [])

  return (
    <div style={{ height: '100%', overflowY: 'auto', padding: 5 }}>
      {loading ? (
        <Spin
          tip="Loading..."
          size="large"
          style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}
        />
      ) : error ? (
        <Alert message="Error" description={error.message} type="error" showIcon />
      ) : (
        <Flex gap="small" wrap align="center">
          {envInfoData &&
            Object.entries(envInfoData).map(([key, value]) => {
              const color = value ? 'green' : 'red'
              return (
                <div key={key} className="m-2">
                  <Badge.Ribbon text={value || '未安装'} color={color}>
                    <Card hoverable={true} className="w-52 p-2">
                      <p>{key}</p>
                    </Card>
                  </Badge.Ribbon>
                </div>
              )
            })}
        </Flex>
      )}
    </div>
  )
}
